/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CreateChangeStaffView.java
 *
 * Created on 19-jan-2010, 10:09:59
 */
package View;

import Controller.Controller;
import Model.Airport;
import Model.PersonalType;
import Model.Rank;
import Model.Staff;
import Util.StringToHtmlConverter;
import crypto.Crypt;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.ToolTipManager;

/**
 *
 * @author Jeroen een sukkel
 */
public class CreateChangeStaffView extends javax.swing.JInternalFrame {

    Staff staff = null;
    boolean newStaff;

    /**
     * Creates new form CreateChangeStaffView
     */
    public CreateChangeStaffView(Staff staff) {
        initComponents();
        this.setTitle("Add User");
        cboType.setModel(new DefaultComboBoxModel(PersonalType.values()));
    
        if (staff != null) {
            this.staff = staff;
            this.newStaff = false;
            txId.setText("" + staff.getId());
            txtName.setText(staff.getName());
            txtUsername.setText(staff.getUsername());
            cboType.setSelectedItem(staff.getType());
            if(staff.getPrimaryAirport()!=null){
            txtAirport.setText(staff.getPrimaryAirport().toString());
            }
            this.setTitle("Change Staff");
            lblPassword.setText("Change password");
        } else {
            this.staff = new Staff();
            this.newStaff = true;
        }
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cboType = new javax.swing.JComboBox();
        txId = new javax.swing.JTextField();
        Name = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        btnSave = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        lblError = new javax.swing.JLabel();
        txtPassword = new javax.swing.JTextField();
        lblId = new javax.swing.JLabel();
        lblName = new javax.swing.JLabel();
        lblUsername = new javax.swing.JLabel();
        lblType = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        lblPassword = new javax.swing.JLabel();
        txtAirport = new javax.swing.JTextField();
        lblAirport = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listSearchResults = new javax.swing.JList();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setMaximumSize(null);
        setMinimumSize(null);
        setName("Form"); // NOI18N
        try {
            setSelected(true);
        } catch (java.beans.PropertyVetoException e1) {
            e1.printStackTrace();
        }
        setVisible(true);

        cboType.setName("cboType"); // NOI18N

        txId.setEditable(false);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(flyaway.FlyAWayApp.class).getContext().getResourceMap(CreateChangeStaffView.class);
        txId.setToolTipText(resourceMap.getString("txId.toolTipText")); // NOI18N
        txId.setName("txId"); // NOI18N
        txId.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                txIdMouseEntered(evt);
            }
        });

        Name.setName("Name"); // NOI18N

        txtName.setName("txtName"); // NOI18N

        btnSave.setText(resourceMap.getString("btnSave.text")); // NOI18N
        btnSave.setToolTipText(resourceMap.getString("btnSave.toolTipText")); // NOI18N
        btnSave.setName("btnSave"); // NOI18N
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnClose.setText(resourceMap.getString("btnClose.text")); // NOI18N
        btnClose.setName("btnClose"); // NOI18N
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        lblError.setName("lblError"); // NOI18N

        txtPassword.setName("txtPassword"); // NOI18N

        lblId.setText(resourceMap.getString("lblId.text")); // NOI18N
        lblId.setName("lblId"); // NOI18N

        lblName.setText(resourceMap.getString("lblName.text")); // NOI18N
        lblName.setName("lblName"); // NOI18N

        lblUsername.setText(resourceMap.getString("lblUsername.text")); // NOI18N
        lblUsername.setName("lblUsername"); // NOI18N

        lblType.setText(resourceMap.getString("lblType.text")); // NOI18N
        lblType.setName("lblType"); // NOI18N

        txtUsername.setText(resourceMap.getString("txtUsername.text")); // NOI18N
        txtUsername.setName("txtUsername"); // NOI18N

        lblPassword.setText(resourceMap.getString("lblPassword.text")); // NOI18N
        lblPassword.setName("lblPassword"); // NOI18N

        txtAirport.setText(resourceMap.getString("txtAirport.text")); // NOI18N
        txtAirport.setName("txtAirport"); // NOI18N
        txtAirport.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtAirportFocusGained(evt);
            }
        });

        lblAirport.setText(resourceMap.getString("lblAirport.text")); // NOI18N
        lblAirport.setName("lblAirport"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        listSearchResults.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listSearchResults.setEnabled(false);
        listSearchResults.setName("listSearchResults"); // NOI18N
        listSearchResults.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listSearchResultsValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listSearchResults);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblError, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(lblName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(lblId, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(lblUsername, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addComponent(lblPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
                                    .addComponent(lblAirport, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtAirport, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE)
                                    .addComponent(txtUsername)
                                    .addComponent(txtName)
                                    .addComponent(txId)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblType, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cboType, 0, 244, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(Name)
                .addGap(63, 63, 63))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblId))
                                .addGap(11, 11, 11)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(lblName)
                                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(11, 11, 11)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblUsername))
                                .addGap(12, 12, 12)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(6, 6, 6)
                                        .addComponent(lblPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtAirport, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblAirport))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(cboType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblType)))
                            .addComponent(jScrollPane1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnSave)
                            .addComponent(btnClose)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(79, 79, 79)
                        .addComponent(Name)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblError, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)
                .addContainerGap())
        );

        getAccessibleContext().setAccessibleDescription(resourceMap.getString("Form.AccessibleContext.accessibleDescription")); // NOI18N

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        if (this.saveStaff()) {
            this.dispose();
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    public boolean saveStaff() {
        //instantatie invoer
        String name = txtName.getText();
        String password = txtPassword.getText();
        String userName = txtUsername.getText();
        PersonalType type = (PersonalType) cboType.getSelectedItem();
        ArrayList<String> errorMessages = new ArrayList<>();

        // bewerken invoer
        name = name.trim();
        userName = userName.trim();
        password = password.trim();
        password = Crypt.encrypt(password);

        // validatie invoer
        if (name.isEmpty()) {
            errorMessages.add("Please enter a name");
        }
        if (userName.isEmpty()) {
            errorMessages.add("Please enter a username");
        }
        if ((newStaff) && (password.isEmpty())) {
            errorMessages.add("Please enter a password");
        }
        
        String foundUserName = Controller.Instance().searchUserName(userName);
        if(newStaff){    
            if(foundUserName != null){
                errorMessages.add("Username already exsists");
            } 
        } else{
            if(foundUserName != null && !foundUserName.equals(this.staff.getUsername())){
                errorMessages.add("You cannot change "+ this.staff.getUsername() + " into "+ userName +  " because it already exsists");
            } 
        }

        // als validatie niet gelukt stop
        if (!errorMessages.isEmpty()) {
            lblError.setText(StringToHtmlConverter.format(errorMessages));
            return false;
        }

        if (this.newStaff) {
            // nieuwe gebruiker aanmaken en opslaan
            staff.setName(name);
            staff.setUsername(userName);
            staff.setType(type);
            staff.setPassword(password, true);
            staff.setRank(Rank.STAFF);

            if (Controller.Instance().save(staff)) {
                JOptionPane.showMessageDialog(this, "Staff " + staff.getName() + " Saved");
                return true;
            }
        } else {
            // bestaande gebruiker bijwerken
            staff.setName(name);
            staff.setUsername(userName);
            staff.setType(type);
            if (!password.isEmpty()) {
                staff.setPassword(password, true);
            }
            staff.setRank(Rank.STAFF);

            if (Controller.Instance().update(staff)) {
                JOptionPane.showMessageDialog(this, "Staff " + staff.getName() + " Saved");
                return true;
            }
        }
        return false;
    }
    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCloseActionPerformed

    private void txIdMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txIdMouseEntered
        txId.setToolTipText("The ID will be automatically generated");
        ToolTipManager.sharedInstance().setInitialDelay(1);
    }//GEN-LAST:event_txIdMouseEntered

    private void listSearchResultsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listSearchResultsValueChanged
        Airport tmpAirport = (Airport) listSearchResults.getSelectedValue();
        if (tmpAirport != null) {
            txtAirport.setText(tmpAirport.toString());
            this.staff.setPrimaryAirport(tmpAirport);
        }
    }//GEN-LAST:event_listSearchResultsValueChanged

    private void txtAirportFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtAirportFocusGained
        txtAirport.setBorder(BorderFactory.createLineBorder(Color.orange));
        listSearchResults.setEnabled(true);
        listSearchResults.setListData(Controller.Instance().getAirports().toArray());
    }//GEN-LAST:event_txtAirportFocusGained

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel Name;
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnSave;
    private javax.swing.JComboBox cboType;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblAirport;
    private javax.swing.JLabel lblError;
    private javax.swing.JLabel lblId;
    private javax.swing.JLabel lblName;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblType;
    private javax.swing.JLabel lblUsername;
    private javax.swing.JList listSearchResults;
    private javax.swing.JTextField txId;
    private javax.swing.JTextField txtAirport;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtPassword;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables
}
